import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { ContentArticleEntity } from '../entity/article';

@Provide()
export class ContentArticleService extends BaseService {
    @InjectEntityModel(ContentArticleEntity)
    contentArticleEntity: Repository<ContentArticleEntity>;

    /**
     * 获取公开的文章列表
     */
    async pageOpen(query: any) {
        const { page = 1, size = 10 } = query;
        const find = this.contentArticleEntity.createQueryBuilder('a')
            .select(['a.id', 'a.title', 'a.cover', 'a.digest', 'a.viewCount', 'a.publishTime', 'a.createTime'])
            .where('a.status = :status', { status: 1 })
            .orderBy('a.publishTime', 'DESC')
            .addOrderBy('a.createTime', 'DESC');

        const [list, total] = await find
            .skip((page - 1) * size)
            .take(size)
            .getManyAndCount();

        return {
            list,
            pagination: {
                page,
                size,
                total
            }
        };
    }

    /**
     * 获取文章详情
     */
    async infoOpen(id: number) {
        const info = await this.contentArticleEntity.findOne({ where: { id, status: 1 } });
        if (info) {
            // 增加浏览量
            await this.contentArticleEntity.increment({ id }, 'viewCount', 1);
        }
        return info;
    }
}

